using UnityEngine;
using System.Collections;

public class Slot
{
	public GameObject prefab;
	public Vector3 m_pos;
	public Vector2 m_tsize;
	public Vector3 m_worldpos;
	public Vector2 m_worldtpos;
	
	int m_nCount;
	
	public ArrayList arr = new ArrayList();
	
	float SPEED = 6.0f;
	float STOPSPEED;
	
	float currentSpeed;
	public enum SlotState
	{
		Stop,
		Start,
		BeginStop
	};
	
	SlotState state = SlotState.Stop;
	
	public void Create(Vector3 pos, Vector2 tSize)
	{
		m_pos = pos;
		m_tsize = tSize;
		
		m_worldpos = new Vector3(MControl.sx + tSize.x / 2 + pos.x, MControl.sy - tSize.y / 2 - pos.y, -pos.z);
		m_worldtpos = new Vector2(m_tsize.x/101, m_tsize.y/10);
	}
	
    public void AddCard(float x, float y, int ID, Texture view)
	{
        GameObject go = Object.Instantiate(prefab) as GameObject;
        MControl cb = (MControl)go.GetComponent(typeof(MControl));
		cb.Id = ID;
		cb.view = view;
        cb.x = m_pos.x + x;
        cb.y = m_pos.y + y;
        cb.depth = m_pos.z+1;
		cb.userdata = this;
        cb.Start();
        arr.Add(cb);
	}
	
	public void Start()
	{
		if( state == SlotState.Stop )
		{
			state = SlotState.Start;
			currentSpeed = SPEED;
		}
	}
	
	public void Stop()
	{
		if( state == SlotState.Start )
		{
			state = SlotState.BeginStop;
			m_nCount = arr.Count;
			STOPSPEED = 0.8f;
		}
	}
	
	public void Update()
	{
		if( state == SlotState.Start )
		{
		}
		else if( state == SlotState.BeginStop )
		{
		}
		else if( state == SlotState.Stop )
		{
			return;
		}
		MControl temp = null;
		for(int i=0; i<arr.Count; ++i)
		{
			MControl c = arr[i] as MControl;
			Vector3 v = c.transform.position;
			if( m_worldpos.y - m_tsize.y > v.y - currentSpeed )
			{
				temp = c;
				if( state == SlotState.BeginStop )
				{
					currentSpeed *= STOPSPEED;
					if( --m_nCount == 0 )
					{
						c.transform.position = new Vector3(m_worldpos.x, m_worldpos.y, m_worldpos.z);
						state = SlotState.Stop;
						return;
					}
				}
			}
			else
			{
				c.transform.position = new Vector3(v.x, v.y - currentSpeed, v.z);
			}
		}
		if( temp != null )
		{
			arr.Remove(temp);
			int i = arr.Count - 1;
			MControl c = arr[i] as MControl;
			temp.transform.position = new Vector3(c.transform.position.x, c.transform.position.y + m_tsize.y, c.transform.position.z);
			arr.Add (temp);
		}
	}
	
	public SlotState State
	{
		get { return this.state; }
		set { this.state = value; }
	}
}
